<?php
/**
 * Matomo 统计API
 * @Copyright (C) 2018 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
//namespace Common\Vendor;
class Matomo{
    private $token_auth='2c72332************';
    private $scheme ='http:';
    private $baseurl = '//tongji.bitefu.net/';
    private $cachedir ='cache/';
    private $configdir ='config/';
    private $domain;
    public function __construct($token_auth='') {
        if(!empty($token_auth))$this->token_auth=$token_auth;
        $this->domain=$_SERVER['HTTP_HOST'];
    }    
    /**
     * 获取站点统计代码
     * @param $domain 域名
     */
    public function getScript($domain=''){
        $SiteIdinfo=$this->getSiteid($domain,1);
        if($SiteIdinfo['status']==0)return false;
        $SiteId=$SiteIdinfo['siteid'];
        $str='<script type="text/javascript">'.
          'var _paq = _paq || [];'.
          '_paq.push([\'trackPageView\']);'.
          '_paq.push([\'enableLinkTracking\']);'.
          '(function() {'.
          'var u="'.$this->baseurl.'";'.
          '_paq.push([\'setTrackerUrl\', u+\'piwik.php\']);'.
          '_paq.push([\'setSiteId\', \''.$SiteId.'\']);'.
          'var d=document, g=d.createElement(\'script\'), s=d.getElementsByTagName(\'script\')[0];'.
          'g.type=\'text/javascript\'; g.async=true; g.defer=true; g.src=u+\'piwik.js\'; s.parentNode.insertBefore(g,s);'.
          '})();'.
          '</script>';
        return $str;
    }
    
    /**
     * 获取查看统计url
     * @param $domain 域名
     * @param $admininfo 管理员账号密码username password
     */
    public function getviewurl($domain='',$admininfo=array()){
        if(empty($domain))$domain=$this->domain;
        $return=array('status'=>0,'info'=>'');
        $SiteIdinfo=$this->getSiteid($domain,1);
        if($SiteIdinfo['status']==0)return false;
        if(empty($admininfo))$admininfo=array('username'=>$domain,'password'=>$domain);
        if($admininfo['username']=='admin')$admininfo['username']=$domain;
        $configpassword=$this->configcache('STATS_CODE');
        if($configpassword!=$admininfo['password']){
            $passwordlength=strlen($configpassword);
            if(empty($configpassword) || $passwordlength!=32){
                $this->addUser($admininfo['username'],$admininfo['password'],$domain);
            }else{
                $this->updateUser($admininfo['username'],$admininfo['password']);
            }
            $result=$this->checkUserAccess($admininfo['username'],$domain);
            if($result){
                $this->configcache('STATS_CODE',$admininfo['password']);
            }
        } 
        $SiteId=$SiteIdinfo['siteid'];
        return $this->scheme.$this->baseurl.'?module=Login&action=logme&login='.$admininfo['username'].'&password='.md5($admininfo['password']).'&idSite='.$SiteId;
    }
    /**
     * 获取站点ID
     * @param $domain 域名
     * @param $is_auto 如果没有是否自动添加
     */
    private function getSiteid($domain='',$is_auto=0){
        if(empty($domain))$domain=$this->domain;
        $return=array('status'=>0,'info'=>'');
        $cachename='Siteid'.$domain;
        $content=$this->cache($cachename);
        if($content){
            $return['status']=1;
            $return['siteid']=$content;
            return $return;
        }
        $param=array(
            'method'=>'SitesManager.getSitesIdFromSiteUrl',
            'url'=>$domain,
        );
        $result=$this->getContent($param);
        if($is_auto && empty($result[0]['idsite'])){
            $result=$this->addSite($domain);
            if(!empty($result['siteid']))$result[0]['idsite']=$result['siteid'];
        }
        if(!empty($result[0]['idsite'])){
            $return['status']=1;
            $return['siteid']=$result[0]['idsite'];
            $this->cache($cachename,$return['siteid']);
        }else{
            $return['info']='暂无';
        }
        return $return;
    }
    /**
     * 添加站点
     * @param $domain 域名
     */
    private function addSite($domain=''){
        if(empty($domain))$domain=$this->domain;
        $return=array('status'=>0,'info'=>'');
        $param=array(
            'method'=>'SitesManager.addSite',
            'siteName'=>$domain,
            'urls'=>$domain,
            'timezone'=>'UTC+8',
        );
        $result=$this->getContent($param);
        if($result['value']){
            $return['status']=1;
            $return['siteid']=$result['value'];
        }else{
            $return['info']='添加失败';
        }
        return $return;
    }
    /**
     * 添加用户
     * @param $username 用户名
     * @param $password密码
     * @param $domain 域名 赋予新增用户域名查看权限
     */
    private function addUser($username,$password='',$domain=''){
        if(empty($username))return false;
        if($username=='admin')$username=$this->domain;
        if(empty($password))$password=md5($password);
        $email='user'.$username.'@hanchao9999.com';
        $param=array(
            'method'=>'UsersManager.addUser',
            'userLogin'=>$username,
            'password'=>$password,
            'email'=>$email,
            'alias '=>$username,
        );
        $result=$this->getContent($param);
        if($result['message']=='ok' && $result['result']=='success')$return= true;
        else if(strpos($result['message'],'already exists')>0)$return= true;
        $return= false;
        if($return && $domain){
            $this->setUserAccess($username,$domain);
        }return $return;
    }
    /**
     * 修改用户
     * @param $username 用户名
     * @param $password密码
     */
    private function updateUser($username,$password=''){
        if(empty($username))return false;
        if($username=='admin')$username=$this->domain;
        if(empty($password))$password=md5($password);
        $email='user'.$username.'@hanchao9999.com';
        $param=array(
            'method'=>'UsersManager.updateUser',
            'userLogin'=>$username,
            'password'=>$password,
            'email'=>$email,
            'alias '=>$username,
        );
        $result=$this->getContent($param);
        if($result['message']=='ok' && $result['result']=='success')return true;
        return false;
    }   
    /**
     * 给会员赋予查看权限
     * @param $username 用户名
     * @param $domain 域名
     */
    private function setUserAccess($username,$domain=''){
        if(empty($username))return false;
        if(empty($domain))$domain=$this->domain;
        if($username=='admin')$username=$domain;
        $SiteIdinfo=$this->getSiteid($domain,1);
        if($SiteIdinfo['status']==0)return false;
        $SiteId=$SiteIdinfo['siteid'];
        $param=array(
            'method'=>'UsersManager.setUserAccess',
            'userLogin'=>$username,
            'access'=>'view',
            'idSites'=>$SiteId,
        );
        $result=$this->getContent($param);
        if($result['message']=='ok' && $result['result']=='success')return true;
        return false;
    }
    
    /**
     * 检查给会员赋予的权限
     * @param $username 用户名
     * @param $domain 域名
     */
    public function checkUserAccess($username,$domain=''){
        if(empty($username))return false;
        if(empty($domain))$domain=$this->domain;
        if($username=='admin')$username=$domain;
        $SiteIdinfo=$this->getSiteid($domain,1);
        if($SiteIdinfo['status']==0)return false;
        $SiteId=$SiteIdinfo['siteid'];
        $param=array(
            'method'=>'UsersManager.getUsersAccessFromSite',
            'idSite'=>$SiteId,
        );
        $result=$this->getContent($param);
        if(empty($result))$return=false;
        $users=array();
        foreach($result as $v){
            foreach($v as $k=>$val){$users[]=$k;}
        }
        if(in_array($username,$users))$return=true;
        if($return)return true;
        return $this->setUserAccess($username,$domain);
    }
    /**
     * 请求api
     * @param $param请求参数
     */
    private function getContent($param){
        if(empty($param))return false;
        $base_param=array(
            'module'=>'API',
            'format'=>'JSON',
            'token_auth'=>$this->token_auth,        
        );
        $params=array_merge($base_param,$param);
        $content=$this->curlget($this->scheme.$this->baseurl,$params);
        return json_decode($content,1);        
    }
    //缓存 可以根据自身情况改造缓存方法
    private function cache($name,$value='',$dir=''){
        if(empty($dir))$dir=$this->cachedir;
        if(empty($value)){
            return @file_get_contents($dir.$name.'.cache');
        }else{
            return file_put_contents($dir.$name.'.cache',$value);
        }
    }
    //配置缓存 根据自己的情况可以改造成存到数据库
    public function configcache($name,$value=''){
        return $this->cache($name,$value,$this->configdir);
    }
    /**
     * CURL发送HTTP请求
     * @param  string $url    请求URL
     * @param  array  $params 请求参数
     * @param  string $method 请求方法GET/POST
     * @param  $header 头信息
     * @param  $multi  是否支付附件
     * @param  $debug  是否输出错误
     * @param  $optsother 附件项
     * @return array  $data   响应数据
     */
    private function curlget($url, $params='', $method = 'GET', $header = array(), $multi = false,$debug=false,$optsother='') {
    	$opts = array(CURLOPT_TIMEOUT => 2,CURLOPT_RETURNTRANSFER=> 1,CURLOPT_SSL_VERIFYPEER=> false,CURLOPT_SSL_VERIFYHOST=> false,CURLOPT_HTTPHEADER => $header);		
    	switch (strtoupper($method)) {/* 根据请求类型设置特定参数 */
    		case 'GET':$opts[CURLOPT_URL] = $params?$url.'?'.http_build_query($params):$url;break;
    		case 'POST':$params = $multi ? $params : http_build_query($params);//判断是否传输文件
        	$opts[CURLOPT_URL] = $url;$opts[CURLOPT_POST] = 1;$opts[CURLOPT_POSTFIELDS] = $params;break;			
    		default:if($debug)echo ('不支持的请求方式！');break;
    	}$ch = curl_init();if($optsother)$opts=array_merge($opts,$optsother);curl_setopt_array($ch, $opts);$data = curl_exec($ch);$error = curl_error($ch);curl_close($ch);/* 初始化并执行curl请求 */
    	if($error && $debug){echo ('请求发生错误:'.$error);}
    	return $data;
    }
}